package com.amigo.online.provider.user.rocketmq.consumer;


import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.amigo.online.common.param.RedisKey;
import com.amigo.online.common.param.result.PhotoInfo;
import com.amigo.online.common.param.result.UserInfo;
import com.amigo.online.provider.user.mapper.UserPhotosMapper;
import com.amigo.online.provider.user.model.entity.UserPhotos;
import com.amigo.online.provider.user.mongo.dao.UserDao;
import com.amigo.online.provider.user.mongo.entity.UserEntity;
import com.amigo.online.provider.user.rocketmq.PushMessage;
import com.amigo.online.provider.user.rocketmq.model.BaseMqSendModel;

@Component("updatePhotoCheck")
public class UpdatePhotoCheck implements PushMessage {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    UserDao userDao;

    @Autowired
    UserPhotosMapper userPhotosMapper;

    @SuppressWarnings("rawtypes")
    @Autowired
    RedisTemplate redisTemplate;


    @SuppressWarnings("unchecked")
    @Override
    public void handleMessage(BaseMqSendModel baseMqSendModel) {
        //处理审核过的照片
        JSONObject json = (JSONObject) baseMqSendModel.getSendContentBean();
        Long id = Long.valueOf((String) json.get("id"));
        Boolean check = (Boolean) json.get("isFace");
        logger.info(id + "-----" + check);
        UserPhotos up = new UserPhotos();
        up.setId(id);
        Integer checked = check ? 1 : 2;
        up = userPhotosMapper.selectByPrimaryKey(up);
        if (up != null && up.getDeleted() != 1) {
            up.setChecked(checked);
            userPhotosMapper.updateByPrimaryKey(up);
        } else {
            return;
        }
        UserEntity user = userDao.getUserById(up.getUserId());
        user.setChecked(checked);
        userDao.saveUser(user);

        UserInfo userInfo = (UserInfo) redisTemplate.opsForHash().get(
                RedisKey.USER_REDIS_KEY, up.getUserId());
        if (userInfo != null) {
            changeFirstImg(userInfo.getPhotos(), checked);
            redisTemplate.opsForHash().delete(RedisKey.USER_REDIS_KEY, up.getUserId());
        }

    }

    private void changeFirstImg(List<PhotoInfo> plist, Integer checked) {
        for (PhotoInfo photoInfo : plist) {
            if (photoInfo.getFirstImg() == 1) {
                photoInfo.setCheck(checked);
                break;
            }
        }
    }
}
